<template>
    <div>
        <!-- {{container}} -->
        <Row>
            <div style="float:left;margin-top:5px;margin-right:10px"  >
                <Button type="primary" style="margin-right:10px" @click="btn_refresh">刷新</Button>
                <Button type="primary" @click="btn_stop_timer">停止定时器</Button>
            </div>
            <!-- 查询区域 -->
            <div style="margin-top:5px;width:700px;margin-right:20px">
                <div style="float:left">
                    <Input v-model="pod_name" disabled />
                </div>
                <div style="width:300px;float:right">
                    <span>选择容器: </span>
                    <Select v-model="container"  style="width: 200px" @on-change="container_changer">
                        <template v-for="c in container_list" >
                            <Option  :key="c" :value="c" v-if="c==container"  selected>{{ c }}</Option>
                            <Option :key="c" :value="c" v-else>{{ c }} </Option>
                        </template>
                    </Select>
                </div>

            </div>
        </Row>
        <div style="height: 80%; margin-top:20px; background: #002833;">
            <div id="terminal" ref="terminal"></div>
        </div>
    </div>
</template>

<script>

import { get_container_name ,get_pod_log} from '@/api'
import { k8s_cluster_post } from '@/api/http'
import { Terminal } from "xterm";
import "xterm/css/xterm.css";
import "xterm/lib/xterm.js";
import {FitAddon} from 'xterm-addon-fit'


export default {
    data() {
        return {
            data: "",
            shellWs: "",
            // 保存terminal实例
            term: "", 
            rows: 40,
            cols: 100,
            oldLen: 0,
            // 容器列表
            container_list:[],
            container: '',
            pod_name: '',
            namespace: '',
        }
    },
    methods: {

        init_T(){
            let _this = this
            // 获取容器宽高/字号大小，定义行数和列数
            // this.rows = document.querySelector(".terminal").offsetHeight / 16 - 6;
            // this.cols = document.querySelector(".terminal").offsetWidth / 14;    
            let term = new Terminal({
                rendererType: "canvas", //渲染类型
                rows: parseInt(_this.rows),
                cols: parseInt(_this.cols),
                // rows: parseInt(40),
                // cols: parseInt(100),
                convertEol: true, //启用时，光标将设置为下一行的开头
                //   scrollback: 50, //终端中的回滚量
                disableStdin: true, //是否应禁用输入。
                cursorStyle: "underline", //光标样式
                cursorBlink: true, //光标闪烁
                // theme: {
                //     foreground: "#000000", //字体
                //     background: "#ffffff", //背景色
                //     cursor: "help", //设置光标
                //     lineHeight: 16
                // }
            })
            term.open(this.$refs["terminal"])

            var fitAddon = new FitAddon()
            term.loadAddon(fitAddon);
            fitAddon.fit();

            window.addEventListener("resize",resizeScreen)
            function resizeScreen(){
                try {
                    fitAddon.fit()
                    term.onResize(()=>{
                        _this.onSend({ Op: "resize", Cols: term.cols, Rows: term.rows });
                    })
                }catch(e){
                    console.log("e", e.message);
                }
            }

            term._initialized = true;

            term.writeln("welcome to lgq terminal")

            _this.term = term

        },
        btn_stop_timer(){
            clearInterval(this.timer)
        },
        container_changer(){
            this.term.clear()
            this.oldLen = 0
            this.refresh()
        },
        get_params(){
            let query = this.$router.currentRoute.query
            let name = query.name

            let namespace = query.namespace
            console.log("namespace:",namespace,"name:",name)            
            this.pod_name =  name
            this.namespace = namespace

            let data = {"namespace":namespace,"name":name}
            // 获取pod内容其的名称
            // [
            //     "flask-admin",
            //     "filebeat",
            //     "istio-proxy"
            // ]
            k8s_cluster_post(get_container_name,data,undefined,undefined).then(response =>{
                let data = response.data
                console.log("获取容其名称:",data)
                this.container_list = data
                this.container = this.container_list[0]
            })
        },
        refresh(){

            let data = {"namespace":this.namespace,"name":this.pod_name,"container":this.container}
            console.log("data:",JSON.stringify(data))
            k8s_cluster_post(get_pod_log,data,undefined,undefined).then(response=>{
                let data = response.data
                // console.log("type:",typeof data)

                let totalLen = data.length
                let newLen = totalLen-this.oldLen
                console.log("total:",totalLen,"old:",this.oldLen,"new:",newLen)
                let newData = data.slice(this.oldLen,totalLen)
                if(newLen > 0){
                    console.log("追加日志")
                    setTimeout(() =>{
                        this.term.writeln(newData)
                    },100); 
                }
                this.oldLen = totalLen
                // this.$refs.xterm.fit()
            }).catch(error=>{
                console.log(error)
            })     
        },
        btn_refresh() {
            this.refresh()
            
        },

    },

    mounted: function() {
        // terminal初始化
        this.get_params()
        this.init_T()
        setTimeout(() =>{
            this.refresh();
        },200); 
        this.timer = setInterval(this.refresh, 10000);
    },
    beforeDestroy() {
        clearInterval(this.timer);
    },

}
</script>
<style>

</style>